import React from 'react';
import { createModalContainer } from '../../../components/changeModal';
import {Button,Input,Form , Icon, message} from 'antd';
import styles from './index.less';
import SelectedImage from '@/components/plugins/selectImage/index';
import InputText from '@/components/Input/index';
import { connect } from 'dva';
const FormItem = Form.Item;

@Form.create()
class Component extends React.Component {
  constructor(props) {
      super(props);
      this.state = {
        imageUrl: props.param.imageUrl,
        isFetching: false,
      }
  }

  
  componentDidMount() {
    window.Isoption = true;
    const url = this.props.param.imageUrl
    if (url){
      this.props.form.setFieldsValue({
          url: url.substr(url.indexOf('.com/') + 5)
      });
    }
}

componentWillMount() {
    window.Isoption = false;
  }

  // 图片插件
  imgModal = ref => {
    this.imgmodal = ref;
  };
  OpenImageModal = () => {
    this.imgmodal.handleShowModal();
  };
  onImageChange = res => {
    this.setState({
      imageUrl: res.imageUrl.substr(res.imageUrl.indexOf('.com/') + 5),
      width: res.width,
      height: res.height
    });
    this.props.form.setFieldsValue({
        url: res.imageUrl.substr(res.imageUrl.indexOf('.com/') + 5)
    });
    this.imgmodal.handleModalVisible();
  };

//取消
handleCancel =() => {
  this.props.cancel();
}
onTextChange = (v) => {
    this.setState({ name: v.target.value  });
    this.props.form.setFieldsValue({
    name: v.target.value 
    })
}


//提交
handleSubmit =e => {
  e.preventDefault();
  const id = this.props.param.secondId;
  const firstId = this.props.param.firstId;
  const {imageUrl, width, height} = this.state;
  const action = this.props.param.action;
  const { dispatch } = this.props;
  this.props.form.validateFields(async (err, values) =>{
      const name = values.name;
      if(!err) {
        if(action ==='addSecondType') {
            dispatch({
                type: 'productClassify/CreateSecondGroup',
                payload: {
                    firstId:firstId,
                    name: name,
                    imgPath: imageUrl,
                },
                callBack: {
                    success: res => {
                        if(res.Code === 0) {
                            message.success('添加成功');
                            this.props.ok(firstId)
                        }
                    },
                    error: res => {
                        message.error(res.Msg);
                    },
                }
            })
          } else {
        dispatch({
            type: 'productClassify/UpdateSecondGroup',
            payload: {
                id: id,
                firstId: firstId,
                name: name,
                imgPath: imageUrl,
            },
            callBack: {
                success: res => {
                    if(res.Code === 0) {
                        message.success('修改成功');
                        this.props.ok();
                    }
                },
                error: res => {
                    message.error(res.Msg);
                },
            }
        })
      }
    }})
   }

    render() {
      const {getFieldDecorator} = this.props.form;
      const {loading1, loading2} = this.props;
      const formItemLayout = {
        labelCol: {
          span: 6 ,
        },
        wrapperCol: {
          span: 8 ,
        },
      };
      const action = this.props.param.action;
      const dataName = this.props.param.firstName;
      const secondName = this.props.param.secondName;
        return (
            <div style={{marginTop: 24}}>
                <SelectedImage onRef={this.imgModal} selectImage={this.onImageChange} />
                <Form onSubmit={this.handleSubmit}>
                    <FormItem label="上级分类" {...formItemLayout}>
                            {getFieldDecorator('type', {
                                initialValue: dataName,
                                rules: [
                                    {required: false, message: '分类不能为空'},
                                ]
                            })(<Input disabled />)}
                        </FormItem>
                    <FormItem label="分类名称" {...formItemLayout}>
                        {getFieldDecorator('name', {
                            initialValue: secondName,
                            rules: [
                                {required: true, message: '分类不能为空'},
                            ],
                            validateTrigger: 'onBlur',
                        })(<InputText onChange={this.onTextChange}  showtotal maxLength={6} autoFocus/>)}
                    </FormItem>
                    <FormItem label="分类图片" className={styles.coverBox} {...formItemLayout}>
                        {getFieldDecorator('url', {
                               rules: [
                                {required: true, message: '分类图不能为空'},
                            ]
                        })(
                            <div className={styles.uploadCover} onClick={this.OpenImageModal}>
                                {this.state.imageUrl ? (
                                    <img
                                    src={
                                        this.props.param.oemInfo &&
                                        this.props.param.oemInfo['cdnUrl'] + '/' + this.state.imageUrl+'?x-oss-process=style/240'
                                    }
                                    style={{ width: '100%', height: '100%' }}
                                    />
                                ) : (
                                    <Icon type="plus" />
                                )}
                            </div>
                        )}                    
                        <span style={{lineHeight: '16px', height: '16px'}}>建议尺寸250*250像素</span>
                    </FormItem>
                    <FormItem className="xkd-model-footBtn">
                        <Button onClick={this.handleCancel} style={{marginRight: 8}}>
                            取消
                        </Button>
                        <Button
                            type="primary"
                            htmlType="submit"
                            loading={loading1||loading2}
                        >
                            保存
                        </Button>
                    </FormItem>
                </Form>
           </div>
        )
    }
}

const SecondType = createModalContainer(
    connect(({productClassify,global, loading}) => ({
        oemInfo: global.oemInfo,
        productClassify:productClassify.productClassify,
        loading1: loading.effects['productClassify/CreateSecondGroup'],
        loading2: loading.effects['productClassify/UpdateSecondGroup'],
    }))(Component),
    true,
    true
);

export default SecondType;
